/*
* 必须引入 commons-httpclient, commons-logging, commons-codec 这三个jar包
*
*/

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
 
import java.io.IOException;
 
public class HttpGetDemo {

    //main 测试方法
    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("http://www.kodejava.org");
 
        try {
            client.executeMethod(method);
 
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }

    //获取url，设置超时，设置编码格式UTF-8
    public String downloadLog(String url) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        String response = null;
        try {
            client.getHttpConnectionManager().getParams()
                    .setConnectionTimeout(10000);
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(method.getResponseBodyAsStream(),
                                "UTF-8"));
                response = reader.readLine();
                reader.close();
            } else {
                logger.warn("downloadLog连接失败:" + method.getStatusCode());
                return null;
            }
        } catch (HttpException e) {
            logger.error("downloadLog获取失败:", e);
            return null;
        } catch (IOException e) {
            logger.error("downloadLog获取失败:", e);
            return null;
        } finally {
            method.releaseConnection();//释放连接
        }
        return response;
    }
    
}